package com.tobby.camel.camelinaction.chapter6.notify;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class OrderClient {

	private final ActiveMQConnectionFactory fac;

	public OrderClient(String url) {
		this.fac = new ActiveMQConnectionFactory(url);
	}

	public void sendOrder(int customerId, Date date, String... itemIds) throws Exception {
		// format the JMSMessage from the input parameters
		String d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date);

		String body = customerId + "," + d;
		for (String id : itemIds) {
			body += "," + id;
		}

		// use JMS code to send the message (a bit ugly code but it works)
		Connection connection = fac.createConnection();
		connection.start();
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createQueue("order");
		MessageProducer producer = session.createProducer(destination);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		Message mes = session.createTextMessage(body);
		producer.send(mes);
		producer.close();
		session.close();
		connection.close();
	}

}
